package com.educate.member.rpc.provide.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.educate.common.utils.converter.ListUtils;
import com.educate.common.utils.exception.AppException;
import com.educate.common.web.BeanUtils;
import com.educate.member.dao.ChildDao;
import com.educate.device.model.bo.ChildBO;
import com.educate.device.model.po.Child;
import com.educate.member.rpc.api.ChildService;
import lombok.extern.log4j.Log4j2;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

@Log4j2
@Service(
        version = "${api.service.version}",
        application = "${dubbo.application.id}",
        protocol = "${dubbo.protocol.id}",
        registry = "${dubbo.registry.id}"
)
public class ChildServiceImpl implements ChildService {

    @Resource ChildDao childDao;

    @Override
    public void create(ChildBO bo) {
        childDao.insert(bo);
    }

    @Override
    public void delete(ChildBO bo) {
        childDao.delete(bo);
    }

    @Override
    public void delete(String childId) {
        childDao.deleteById(childId);
    }

    @Override
    public ChildBO detail(String childId) {
        Optional<Child> optional = childDao.findById(childId);
        if (!optional.isPresent()) {
            throw new AppException("不存在的实例");
        }
        return new ChildBO(optional.get());
    }

    @Override
    public ChildBO detail(ChildBO bo) {
//        return detail(bo.getOrganizationId());
        return null;
    }

    @Override
    public void update(ChildBO bo) {
        Optional<Child> optional = childDao.findById(bo.getChildId());
        if (!optional.isPresent()) {
            throw new AppException("不存在的实例");
        }
        BeanUtils.copyPropertiesNonEmpty(bo, optional.get());
        childDao.save(optional.get());
    }

    @Override
    public Page<ChildBO> query(ChildBO bo, PageRequest pageRequest) {
        return childDao.query(bo, pageRequest).map(ChildBO::new);
    }

    @Override
    public List<ChildBO> list(ChildBO bo) {
        List<Child> result = childDao.findAll();
        return ListUtils.map(result, ChildBO::new);
    }
}
